package edu.bbu.commonproject.backend.logic.utils;

import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

/**
 * This is the MailService class.
 * With this class you can send mails to users.
 */
public class MailService
{
	private final String userName;
	private final String userPassword;
	
	private Properties properties;
	private Session session;
	
	/**
	 * This is the MailService class constructor.
	 * The userName is your email address and the userPassword is your password.
	 * @param userName
	 * @param userPassword
	 */
	public MailService(final String userName,final String userPassword)
	{
		this.userName = userName;
		this.userPassword = userPassword;
		
		this.properties = new Properties();
	    this.properties.put("mail.smtp.starttls.enable", "true");
	    this.properties.put("mail.smtp.auth", "true");
	    this.properties.put("mail.smtp.host", "smtp.gmail.com");
	    this.properties.put("mail.smtp.port", "587");
	    
	    this.session = Session.getInstance(properties, new Authenticator() 
	    {
	    	protected PasswordAuthentication getPasswordAuthentication() 
	    	{
	    		return new PasswordAuthentication(userName, userPassword);
	        }
	    });
	    
	}
	
	/**
	 * This method send an email to the address with subject and messageText. 
	 * @param address
	 * @param subject
	 * @param messageText
	 * @throws MessagingException
	 */
	public void sendEmail(String address, String subject, String messageText) throws MessagingException
	{
		Message message = new MimeMessage(session);
		message.setFrom(new InternetAddress(userName));

		message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(address));
		message.setSubject(subject);
		message.setText(messageText);

		Transport.send(message);
	}	
	
}
